<template>
	<view class="home_content" :style="{ height: `calc(100vh - ${statusBarHeight}rpx)` }" >
        <view class="home_header">
            <text @click="scan" class="iconfont icon-saoma"></text>
            <view class="easy_input">
                <input placeholder="请输入 搜索号/款号/款色编号" v-model="form.search" />
                <button :plain="true" @click="handleSearch" >搜索</button>
            </view>
            <view  class="easy_select">
                <uni-data-select
                    v-model="form.filtrate"
                    placeholder="默认排序"
                    :localdata="filtrList"
                    @change="changeFliter"
                    ></uni-data-select>
            </view>
            <button @click="showDrawer" :plain="true" class="filter_btn">
                <view>筛选</view>
                <text class="iconfont icon-shaixuan"></text>
            </button>

        </view>
        <view class="home_swiper">
            <swiper class="swiper" circular :indicator-dots="true" :autoplay="true" :interval="3000"
				:duration="500">
				<swiper-item v-for="(item, index) in swiperList" :key="index">
                    <image style="width: 100%; height: 100%;" mode="scaleToFill" :src="item.src" />
				</swiper-item>
			</swiper>
        </view>


        <view class="home_goods">
            <scroll-view style="height: 100%;" scroll-y="true" @scrolltolower="onScrolltolower">
                <view class="custom_box">
                    <view class="custom_grid" v-for="(item, index) in goodList" :key="index">
                        <view class="goods_grid_info" @click="addGoodsPopup(item)">
                            <image style="width: 100%; height: 120rpx; border-radius: 5rpx;" mode="scaleToFill" :src="item.hhImg" />
                            <view class="info_title">{{item.huohao || ''}}</view>
                            <view class="info_des_content">{{ item.huohaoname || '' }}</view>
                            <view class="info_item">
                                <view class="info_des">￥ {{ item.xsprice || 0 }}</view>
                                <text class="iconfont icon-gouwuche"></text>
                            </view>
                        </view>
                    </view>
                </view>
            </scroll-view>

            <!-- 商品类别 横向排列 -->
            <!-- <scroll-view style="height: 100%;" scroll-y="true">
                <view class="home_goods_item" v-for="(item, index) in goodList" :key="index" @click="goDetailPopup(item)">
                    <view class="goods_img">
                        <image style="width: 100%; height: 100%; border-radius: 20rpx;" mode="scaleToFill" :src="item.img" />
                    </view>
                    <view class="goods_info">
                        <view class="goods_info_item">
                            <view class="label">货号：</view>
                            <view class="item_content">{{ item.huohao }}</view>
                        </view>
                        <view class="goods_info_item" style="flex: 1;">
                            <view class="label">名称：</view>
                            <textarea class="item_content" disabled v-model="item.name" auto-height />
                        </view>
                        <view class="goods_info_item">
                            <view style="display: flex; align-items: center; flex: 1;">
                                <view class="label">价格：</view>
                                <view class="item_content">￥ {{ item.price }}</view>
                            </view>
                            <text class="iconfont icon-gouwuche"></text>
                        </view>
                    </view>
                </view>
            </scroll-view> -->
        </view>

        <!-- 弹出购物组件 -->
        <addGoods
            ref="addGoodsChild"
            @childAddGoods="childAddGoods"
            ></addGoods>
        
        <!-- 筛选侧边弹出层 -->
        <uni-drawer ref="showRight" :width="600" mode="right">
			<view class="drawer_content">
                <view class="drawer_header">
                    <view class="title">
                        <text @click="closeDrawer" class="iconfont icon-shanchu"></text>
                        <view>筛选</view>
                        <view></view>
                    </view>

                    <view class="subtitle">
                        大类
                    </view>
                </view>
                <view class="drawer_center">
                    <scroll-view style="height: 100%;" scroll-y="true">
                        <view class="scroll_view">
                            <view 
                                class="drawer_item" 
                                :class="{active: item.active}"
                                @click="changeType(item, index)"
                                v-for="(item, index) in typeList" :key="index">
                                {{ item.name }}
                                <text @click="closeDrawer" class="iconfont" :class="{'icon-dagou': item.active}"></text>
                            </view>
                        </view>
                    </scroll-view>
                </view>
                <view class="drawer_footer">
                    <button hover-class="hover_reset" @click="handleReset">重置</button>
                    <button hover-class="hover_save" @click="handleSave">确定</button>
                </view>
            </view>
		</uni-drawer>

	</view>
</template>

<script>
import BottomPopup from '@/components/custom-bottom-popup/custom-bottom-popup.vue'; // 引入自定义组件
import addGoods from '@/components/add-goods/add-goods.vue'; // 引入自定义组件
import utils from "@/utils/utils.js";
import Http from '@/service/api'
import { mapState, mapMutations, mapActions } from "vuex";
	export default {
        components: {
			BottomPopup,
            addGoods,
		},
		data() {
			return {
               statusBarHeight: 0,
               form: {},
               filtrList: [
                    { value: '默认排序', text: "默认排序" },
                    { value: '最新发布', text: "最新发布" },
                    { value: '价格高到低', text: "价格高到低" },
                    { value: '价格低到高', text: "价格低到高" },
                    { value: '库存数量', text: "库存数量" },
                ],
                typeList: [
                    { value: 1, name: '推荐', active: true,  },
                    { value: 2, name: '上架', active: false,  },
                    { value: 3, name: '芭比裤', active: false,  },
                    { value: 4, name: '2024保暖衣', active: false,  },
                    { value: 5, name: '2024羽绒服', active: true,  },
                    { value: 6, name: '2024上衣', active: false,  },
                    { value: 7, name: '2024夏防晒衣', active: true,  },
                ],
                swiperList: [
                    { src: '../../static/login/1.jpg' },
                    { src: '../../static/login/2.jpg' },
                    { src: '../../static/login/3.jpg' },
                    { src: '../../static/login/4.jpg' },
                ],
                goodList: [],

                page: 1,
                size: 20,
                huohaotype: '', // 货号编号
                showLower: false, // 是否触底加载更多
			}
		},
        created() { // 子组件 onLoad 不生效 
			this.statusBarHeight = this.$globalMap.statusBarHeight
            console.log('== height home ', this.statusBarHeight)

            let a = []
            for(let i=0; i<13; i++) {
                a.push({
                    img: `../../static/login/${i+1 < 14 ? i+1 : 5}.jpg`,
                    price: i,
                    des: '啊未发货那色粉啊数据恢复us根据分工合适高度分公司加工费好几十个地方色粉舒服点',
                    chimaList: [
                        { chima: 'S', num: 1 },
                        { chima: 'M', num: 0 },
                        { chima: 'L', num: 2 },
                        { chima: 'XL', num: 0 },
                        { chima: '2XL', num: 0 },
                        { chima: '3XL', num: 0 },
                        { chima: '4XL', num: 0 },
                        { chima: '5XL', num: 0 },
                        { chima: '6XL', num: 0 },
                        { chima: '7XL', num: 0 },
                        { chima: '8XL', num: 0 },
                        { chima: '9XL', num: 0 },
                    ], 
                    colorList: [
                        { color: '灰色', num: 100 },
                        { color: '黑生', num: 0 },
                        { color: '米白', num: 84 },
                        { color: '深灰', num: 0 },
                        { color: '卡其色', num: 0 },
                        { color: '军绿1', num: 5 },
                        { color: '军绿2', num: 0 },
                        { color: '军绿3', num: 0 },
                        { color: '军绿4', num: 0 },
                        { color: '军绿5', num: 0 },
                        { color: '军绿6', num: 0 },
                        { color: '军绿7', num: 0 },
                        { color: '军绿8', num: 0 },
                        { color: '军绿9', num: 0 },
                        { color: '军绿10', num: 0 },
                        { color: '军绿11', num: 0 },
                    ], 
                })
            }
            // this.goodList = utils.splitArray(a, 4) 
            // this.goodList = a // 删掉 


            this.getHuohaoPageList()
            this.GetBaseInfoList()
		},
        computed: {
            activeTypeCom() {
                return this.typeList.filter(i => i.active).length ? false : true
            },
            ...mapState([
                "userCart",
            ]),
        },
		methods: {
             // 侧边栏获取基础数据
             GetBaseInfoList() {
                let param = { param: 'huohaotype' }
                Http.GetBaseInfoList(param).then(r => {
                    this.typeList = r.huohaotype.map(i => ({...i, active: false}))
                }).catch(err => {
                    console.log('== err ', err)
                })
            },
            handleSearch() {
                this.showLower = false
                this.page = 1
                this.getHuohaoPageList()
            },
            changeFliter(e) {
                this.showLower = false
                this.page = 1
                this.getHuohaoPageList()
            },
            showDrawer() {
                this.$refs.showRight.open();
            },
            closeDrawer() {
                this.$refs.showRight.close();
            },
            scan() {
                console.log('== 扫描')
            },
            changeType(item, index) {
                this.typeList = this.typeList.map(i => ({...i, active: i.bh == item.bh ? !i.active : i.active}))
            },
            handleReset() {
                this.typeList = this.typeList.map(i => ({...i, active: false}))
            },
            handleSave() {
                let activeStr = this.typeList.filter(i => i.active).map(i => i.bh).join(',')
              
                this.showLower = false
                this.page = 1
                this.huohaotype = activeStr
                this.getHuohaoPageList()
                this.$refs.showRight.close();
            },
            // goDetailPopup() { // 打开底部弹出框
            //     this.$refs.bottomPopup.showPopup();
            //     console.log('== 显示 11')
            // },


            addGoodsPopup(item) {
                console.log(' == userCart ', this.userCart)
                // 父组件 调用 子组件 的方法
                Http.getHuohaoQueryInfo({ huohaobh: item.huohao }).then(r => {
                    this.$refs.addGoodsChild.goDetailPopup(r, 0)
                }).catch(err => {
                    uni.showToast({
                        title: err.message,
                        icon: 'none'
                    });
                })
            },
            // 子传父 保存的数据
            childAddGoods(goodsMap) {
                console.log('== 详情 goodsMap ', goodsMap)
                let userCart = {
                    ...goodsMap,
                    hjPrice: (Number(goodsMap.main.xsprice) || 0) * goodsMap.hjsl,
                    colorList: goodsMap.colorList.filter(i => i.num).map(i => ({...i, chimaList: i.chimaList.map(j => ({...j, check: false})) })),
                    itemCheck: false,
                }

                let a = this.mergeArrays(this.userCart, [userCart])
                this.addCart_x(a) // 加入购物车
                uni.showToast({
                    title: '添加成功',
                    icon: 'none'
                });
                this.$refs.addGoodsChild.closeDrawer() // 关闭 弹出框 
            },


            onScrolltolower() {
                this.page++
                this.showLower = true
                console.log('== 加载跟多  ', this.page)
                this.getHuohaoPageList()
            },

            getHuohaoPageList() {
                let param = {
                    page: this.page,
                    size: this.size,
                    search: this.form.search, 
                    huohaotype: this.huohaotype,
                    scheme: this.form.filtrate,
                }

                console.log('== param ', param)

                Http.getHuohaoPageList(param).then(r => {
                    console.log('== r 商品 -- ', r)
                    // let data = r.map(i => ({...i, detail: utils.splitArray(i.detail, 3)}))
                    let data = r
                    if (!data.length && this.showLower) {
                        uni.showToast({
                            title:'数据加载完毕',
                            icon:'none',
                            duration:3000  
                        })
                        this.page--;
                        return
                    }
                    if (this.showLower) {
                        this.goodList = this.goodList.concat(data)
                    } else {
                        this.goodList = data
                    }
                }).catch(err => {
                    console.log('== err 11 ', err)
                })
            },

            // 添加购物车 封装函数
            mergeArrays(arr, arr2) {
                arr2.forEach(item2 => {
                    const foundIndex = arr.findIndex(item => item.main.huohao === item2.main.huohao);

                    if (foundIndex !== -1) {
                        // 如果找到了相同的 huohao，更新 hjsl 和 hjPrice
                        arr[foundIndex].hjsl += item2.hjsl;
                        arr[foundIndex].hjPrice += item2.hjPrice;

                        // 更新 colorList
                        item2.colorList.forEach(colorItem2 => {
                            const colorItemIndex = arr[foundIndex].colorList.findIndex(colorItem => colorItem.color === colorItem2.color);

                            if (colorItemIndex !== -1) {
                                // 如果找到了相同的颜色，更新 num
                                arr[foundIndex].colorList[colorItemIndex].num += colorItem2.num;

                                // 更新 chimaList
                                colorItem2.chimaList.forEach(chimaItem2 => {
                                    const chimaItemIndex = arr[foundIndex].colorList[colorItemIndex].chimaList.findIndex(chimaItem => chimaItem.chima === chimaItem2.chima);

                                    if (chimaItemIndex !== -1) {
                                        // 如果找到了相同的尺码，更新 num
                                        arr[foundIndex].colorList[colorItemIndex].chimaList[chimaItemIndex].num += chimaItem2.num;
                                    } else {
                                        // 如果没有找到，添加新的尺码
                                        arr[foundIndex].colorList[colorItemIndex].chimaList.push({ ...chimaItem2 });
                                    }
                                });
                            } else {
                                // 如果没有找到，添加新的颜色
                                arr[foundIndex].colorList.push({ ...colorItem2 });
                            }
                        });
                    } else {
                        // 如果没有找到相同的 huohao，直接 push 到 arr
                        arr.push({ ...item2 });
                    }
                });

                return arr;
            },
            ...mapMutations([
                "addCart_x",
            ]),
		}
	}
</script>

<style lang="less" scoped>
.home_content {
    height: 100vh;
    background: #d1d1d1;
    display: flex;
    flex-direction: column;
    font-size: 16rpx;

    .home_header {
        display: flex;
        align-items: center;
        background: #fff;
        padding: 10rpx;

        .iconfont {
            font-size: 35rpx;
            margin-right: 10rpx;
        }

        .easy_input {
            flex: 1;
            display: flex;
            align-items: center;
            border: 1rpx solid #ccc;
            margin-right: 10rpx;
            input {
                flex: 1;
                padding: 10rpx;
            }

            button {
                margin: 0;
                border: none;
                border-left: 2rpx solid #ccc;
            }
        }

        .easy_select {
            width: 110rpx;
            margin-right: 10rpx;
            /deep/.uni-select {
                height: 43rpx;
                border: 1rpx solid #ccc;
            }
        }

        .filter_btn {
            display: flex;
            align-items: center;
            height: 43rpx;
            border: 1rpx solid #ccc;
            .iconfont {
                font-size: 20rpx;
                margin-left: 10rpx;
            }
        }
    }

    .home_swiper {
        height: 300rpx;
        .swiper {
            height: 100%;
        }
    }

	.home_goods {
       flex: 1;
       background: #ededed;
       overflow: auto;
       padding: 0 3rpx;
       padding-top: 5rpx;

        // 
        .custom_box {
            display: flex;
            flex-wrap: wrap;
            overflow: hidden;
            background: #e5e5e5;

            .custom_grid {
                width: 24.6%;
                padding: 1rpx;
                overflow: hidden;
            }
        }
        // 



       .home_goods_item {
            display: flex;
            margin-bottom: 10rpx;
            background: #fff;

            /deep/ .uni-grid-item {
                height: 240rpx !important;
                background: #fff;
            }

            .goods_img {
                width: 200rpx;
                height: 200rpx;
            }
       }

       .goods_info {
        flex: 1;
            display: flex;
            flex-direction: column;
            padding: 10rpx;

            .goods_info_item {
                display: flex;
                padding-bottom: 10rpx;
                .label {
                    width: 70rpx;
                }

                .item_content {
                    flex: 1;
                    font-size: 20rpx;
                }

                .iconfont {
                    font-size: 30rpx;
                    padding-right: 10rpx;
                    color: #faba70;
                }
            }
       }
	}
}

// 侧边弹出层
.drawer_content {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background: #fff;
    padding: 20rpx;
    .drawer_header {
        padding-bottom: 10rpx;
        font-size: 25rpx;
        .title {
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1rpx solid #ccc;
            padding-bottom: 20rpx;

            .iconfont {
                font-size: 40rpx;
            }
        }

        .subtitle {
            padding: 20rpx 0;
            border-bottom: 1rpx dashed  #ccc;
        }
    }

    .drawer_center {
        overflow-x: auto;
        flex: 1;

        .scroll_view {
            display: flex;
            flex-wrap: wrap;
        }

        .drawer_item {
            font-size: 20rpx;
            position: relative;
            background: #f5f5f5;
            padding: 10rpx 20rpx;
            min-width: 100rpx;
            margin: 10rpx;
            text-align: center;

            .iconfont {
                position: absolute;
                top: 0;
                right: 0;
                color: #ff8b05;
            }
        }

        .active {
            background: #ffedd8;
            color: #ff8b05;
        }
    }

    .drawer_footer {
        border-top: 1rpx solid #ccc;
        padding-top: 10rpx;
        padding-bottom: 30rpx;
        display: flex;
        align-items: center;

        button {
            margin: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #000;
            background: #fff;
            width: 100rpx;
            height: 60rpx;
        }

        button:nth-child(2) {
            background: #ff8b05;
            color: #fff;
            flex: 1;
        }

        .hover_reset {
            background: #c7c7c7;
        }
        .hover_save {
            background: #ce7005 !important;
        }
    }
}

// 底部弹出框
.popup_content {
    height: 75vh;

    .popup_header {
        display: flex;
        position: relative;
        .popup_img {
            position: absolute;
            width: 200rpx; 
            height: 200rpx;
            bottom: 0rpx;
        }

        .popup_info {
            position: relative;
            flex: 1;
            background: #ccc;
            margin-left: 20rpx;

            .info_item {
                display: flex;
                align-items: center;
                padding-bottom: 5rpx;

                .item_right {
                    flex: 1;
                    background: #d1d1d1;
                }
            }

            .iconfont {
                font-size: 40rpx;
                position: absolute;
                top: -10rpx;
                right: -10rpx;
                color: #9a9a9a;
            }
        }
    }
}

// 方格子显示 商品
.goods_grid_info {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    background: #fff;

    .info_item {
        display: flex;
        align-items: center;
        padding: 0 10rpx;
        padding-bottom: 5rpx;
        font-size: 20rpx;
    }

    .info_title {
        font-size: 20rpx;
        margin-bottom: 2rpx;
        padding: 0 10rpx;
    } 

    .info_des {
        flex: 1;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .info_des_content {
        padding: 0 10rpx;
        flex: 1;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 3; /* 显示三行 */
        overflow: hidden; /* 超出部分隐藏 */
        text-overflow: ellipsis; /* 超出部分显示省略号 */
    }
    .iconfont {
        font-size: 20rpx;
        color: #ff8800;
        padding-right: 15rpx;
    }
}

</style>
